import React, { useState, useEffect} from "react";
import {Poloscope} from '@marvintau/poloscope';
import AutoSizer from "react-virtualized-auto-sizer";

import Header from './Header';
import useEdit from './useEdit';
import useCascadeNavigator from './useCascadeNavigator';

import {makeRow, makeFilterRow} from './makeRow'; 

import './nest.css';

const editableCols = (cols, editable) => {
  return editable
  ? {...cols, edit: {desc:'编辑', width: 160, editControl: true}}
  : cols
}

export default function({data:origData, cols: origCols, editable}){

  const data = Array.isArray(origData) ? origData : origData?.succ ?? [];

  // Update whole poloscope when the original data changes.
  const [updateKey, setUpdateKey] = useState('NEW');
  useEffect(() => {
    setUpdateKey(Math.random().toString(35).slice(2, 7));
  }, [data])

  // Update when original cols Changes
  const [cols, setCols] = useState(editableCols(origCols, editable));
  useEffect(() => {
    setCols(editableCols(origCols, editable));
  }, [origCols, editable])

  // Update when adjusted col width.
  const setColWidth = (key, width) => {
    const col = {...cols[key], width};
    const newCols = {...cols, [key]: col};
    setCols(newCols);
  }

  // Initialize cascade navigator.
  const {
    history,
    sublist,
    enter,
    leave
  } = useCascadeNavigator(data, editable);

  // Initialize edit hook with sublist;
  const {
    data:filteredData,
    filterApplied,
    sort,
    filter,
    updateProp,
    editMethods,
  } = useEdit(sublist);

  const SublistRow = makeRow({
    cols,
    select: enter,
    sticky: false,
    disabled: filterApplied,
    updateProp,
    editMethods, 
  })

  const HistoryRow = makeRow({cols, select: leave, sticky: true})

  const FilterRow = makeFilterRow(cols, editMethods);

  return <div className="nest-view hidden-scroll">
    <AutoSizer disableWidth={true}>{
      ({height}) => 
        <Poloscope {...{key:updateKey, buffer: 40, itemData:filteredData, Row:SublistRow, height}}>
          <Header {...{setColWidth, cols}} />
          {history.map((_, index) => {
            return <HistoryRow {...{key: index, index, data: history}} />
          })}
          <FilterRow filterCol={filter} sortCol={sort} />
        </Poloscope>
    }</AutoSizer>
  </div>

}
